from django.test import TestCase
from django.shortcuts import reverse
from django.contrib.auth.models import User

from .models import Item, Cart, Category

class TestCartDelete(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='test_user', password='pass')
        self.item = Item.objects.create(name='test item', created_by=self.user, price=10,
                                        category=Category.objects.create(name='cate'))
        self.cart = Cart.objects.create(user=self.user, item=self.item)

    def test_get_method_not_allow(self):
        self.client.force_login(self.user)
        rep = self.client.get(reverse('cart_delete', kwargs={'cart_id': self.cart.id}))
        self.assertEqual(rep.status_code, 405)
        self.assertEqual(Cart.objects.count(), 1)

    def test_only_user_can_delete_own_cart(self):
        user2 = User.objects.create_user(username='test_user2', password='pass')
        self.client.force_login(user2)
        rep = self.client.post(reverse('cart_delete', kwargs={'cart_id': self.cart.id}))
        self.assertEqual(rep.status_code, 200)
        self.assertEqual(Cart.objects.count(), 1)


class TestCartAdd(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='test_user', password='pass')
        self.item = Item.objects.create(name='test item', created_by=self.user, price=10,
                                        category=Category.objects.create(name='cate'))

    def test_add_item_by_user_fail(self):
        self.client.force_login(self.user)
        rep = self.client.post(reverse('cart_add', kwargs={'item_id': self.item.id}))
        self.assertEqual(rep.status_code, 200)
        self.assertEqual(Cart.objects.count(), 0)

    def test_add_same_item_set_quantity_plus_1(self):
        user2 = User.objects.create_user(username='test_user2', password='pass')
        self.client.force_login(user2)
        rep = self.client.post(reverse('cart_add', kwargs={'item_id': self.item.id}),
                               {'quantity': 1})
        self.assertEqual(rep.status_code, 302)
        self.assertEqual(Cart.objects.count(), 1)
        cart = Cart.objects.filter(item=self.item, user=user2).first()
        self.assertEqual(cart.quantity, 1)
        rep = self.client.post(reverse('cart_add', kwargs={'item_id': self.item.id}),
                               {'quantity': 1})
        cart = Cart.objects.filter(item=self.item, user=user2).first()
        self.assertEqual(cart.quantity, 2)
        rep = self.client.post(reverse('cart_add', kwargs={'item_id': self.item.id}),
                               {'quantity': cart.quantity})
        cart = Cart.objects.filter(item=self.item, user=user2).first()
        self.assertEqual(cart.quantity, 3)